﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ConfigDashboard.Models
{
    public class ConfigSettingValueRow
    {
        public ConfigSettingName SettingName { get; set; }
        public Dictionary<ConfigEnvironment, ConfigSettingValue> Values { get; set; }

        public ConfigSettingValueRow(ConfigSettingName settingName)
        {
            SettingName = settingName;
            Values = new Dictionary<ConfigEnvironment, ConfigSettingValue>();
        }
    }


    public class ValuesViewModel
    {
        private ConfigSettingsEntities db = new ConfigSettingsEntities();
        private IEnumerable<ConfigEnvironment> _environments = null;

        public IEnumerable<ConfigEnvironment> Environments
        {
            get
            {
                if (null == _environments)
                    _environments = db.ConfigEnvironments.ToList();
                return _environments;
            }
        }


        public IEnumerable<ConfigSettingValueRow> Settings
        {
            get
            {
                var rows = new List<ConfigSettingValueRow>();
                var configsettingnames = db.ConfigSettingNames.Include("ConfigSettingValues.ConfigEnvironment").OrderBy(n => n.ViewOrder);
                var names = configsettingnames.ToList();

                foreach (var name in names)
                {
                    var row = rows.FirstOrDefault(r => r.SettingName == name);
                    if (null == row)
                    {
                        row = new ConfigSettingValueRow(name);
                        rows.Add(row);
                    }

                    foreach (var value in name.ConfigSettingValues)
                    {
                        row.Values[value.ConfigEnvironment] = value;
                    }
                }

                return rows;
            }
        }
    }
}